package com.ruoyi.walmart.service.shipments.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.walmart.domain.shipments.Shipment;
import com.ruoyi.walmart.domain.shipments.ShipmentLabel;
import com.ruoyi.walmart.mapper.shipments.ShipmentLabelMapper;
import com.ruoyi.walmart.mapper.shipments.ShipmentMapper;
import com.ruoyi.walmart.service.shipments.ShipmentLabelService;
import com.ruoyi.walmart.service.shipments.ShipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class ShipmentLabelServiceImpl implements ShipmentLabelService {

    @Autowired
    ShipmentLabelMapper shipmentLabelMapper;

    @Autowired
    ShipmentMapper shipmentMapper;
    /**
     * 保存入库件pdf
     * @return
     */
    @Override
    @Transactional
    public void saveShipmentLabelPdf(byte[] pdfData, ShipmentLabel shipmentLabel) {

        // 数据库资源地址
        String localPath = RuoYiConfig.getProfile();
        // 获取当前年月，例如 "202502"
        String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));

        String nextFile = "shipmentLabel";

        String shipmentId = shipmentLabel.getShipmentId();

        // 构建完整的文件夹路径: shipmentLabel/202502
        Path shipmentLabelPath = Paths.get(localPath, nextFile, yearMonth);
        try {
            // 检查并创建文件夹（如果不存在的话）
            if (!Files.exists(shipmentLabelPath)) {
                Files.createDirectories(shipmentLabelPath);
            }

            // 定义文件路径（例如: shipmentLabel/202502/label.pdf）
            String filePath = shipmentLabelPath.resolve(shipmentId+".pdf").toString();

            // 将PDF字节数据写入文件
            Files.write(Paths.get(filePath), pdfData);

            String path = "/"+nextFile+"/"+yearMonth+"/"+shipmentId+".pdf";
            shipmentLabel.setShipmentLabelPath(path);

            QueryWrapper<ShipmentLabel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shipment_id", shipmentId); // 根据 shipmentId 字段查询

            ShipmentLabel select = shipmentLabelMapper.selectOne(queryWrapper);
            if(select != null){
                shipmentLabelMapper.deleteById(select.getId());
            }
            //插入标签值
            shipmentLabelMapper.shipmentLabelInsert(shipmentLabel);

            //更新主表状态为CREATED,模仿店铺后台的状态。
            Shipment shipment = new Shipment();
            shipment.setShipmentId(shipmentId);
            shipment.setStatus("CREATED");
            shipmentMapper.updatedShipmentStatus(shipment);

        } catch (IOException e) {
            throw new ServiceException("写入PDF文件失败");
        }

    }
}
